package com.example.teemor.es_demo.service;

import com.example.teemor.es_demo.entity.UserBehaviorLog;
import com.example.teemor.es_demo.entity.UserProfile;
import com.example.teemor.es_demo.entity.HotProduct;
import com.example.teemor.es_demo.entity.OrderItem;
import com.example.teemor.es_demo.repository.clickhouse.UserBehaviorRepository;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import jakarta.servlet.http.HttpServletRequest;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.List;
import java.util.Map;
import java.util.UUID;

@Slf4j
@Service
@RequiredArgsConstructor
public class UserBehaviorService {

    private final UserBehaviorRepository userBehaviorRepository;

    /**
     * 记录用户行为日志
     */
    @Async
    public void recordUserBehavior(Long userId, String sessionId, String eventType, 
                                 Long productId, String category, String searchKeyword,
                                 String pageUrl, HttpServletRequest request) {
        try {
            UserBehaviorLog logEntity = new UserBehaviorLog();
            logEntity.setId(System.currentTimeMillis()); // 使用时间戳作为ID
            logEntity.setUserId(userId);
            logEntity.setSessionId(sessionId != null ? sessionId : UUID.randomUUID().toString());
            logEntity.setEventType(eventType);
            logEntity.setProductId(productId);
            logEntity.setCategory(category);
            logEntity.setSearchKeyword(searchKeyword);
            logEntity.setPageUrl(pageUrl);
            logEntity.setUserAgent(request.getHeader("User-Agent"));
            logEntity.setIpAddress(getClientIpAddress(request));
            logEntity.setTimestamp(LocalDateTime.now());
            logEntity.setDate(LocalDateTime.now());
            
            userBehaviorRepository.saveUserBehaviorLog(logEntity);
            log.info("User behavior recorded: userId={}, eventType={}, productId={}", 
                    userId, eventType, productId);
        } catch (Exception e) {
            log.error("Failed to record user behavior", e);
        }
    }

    /**
     * 记录页面浏览行为
     */
    public void recordPageView(Long userId, String sessionId, String pageUrl, HttpServletRequest request) {
        recordUserBehavior(userId, sessionId, "view", null, null, null, pageUrl, request);
    }

    /**
     * 记录商品浏览行为
     */
    public void recordProductView(Long userId, String sessionId, Long productId, 
                                String category, HttpServletRequest request) {
        recordUserBehavior(userId, sessionId, "view", productId, category, null, 
                          "/product/" + productId, request);
    }

    /**
     * 记录搜索行为
     */
    public void recordSearch(Long userId, String sessionId, String searchKeyword, 
                           String category, HttpServletRequest request) {
        recordUserBehavior(userId, sessionId, "search", null, category, searchKeyword, 
                          "/search", request);
    }

    /**
     * 记录点击行为
     */
    public void recordClick(Long userId, String sessionId, Long productId, 
                          String category, HttpServletRequest request) {
        recordUserBehavior(userId, sessionId, "click", productId, category, null, 
                          "/product/" + productId, request);
    }

    /**
     * 记录加购物车行为
     */
    public void recordAddToCart(Long userId, String sessionId, Long productId, 
                               String category, HttpServletRequest request) {
        recordUserBehavior(userId, sessionId, "add_cart", productId, category, null, 
                          "/cart/add", request);
    }

    /**
     * 记录购买行为
     */
    public void recordPurchaseBehavior(Long userId, List<OrderItem> orderItems) {
        try {
            String sessionId = UUID.randomUUID().toString();
            for (OrderItem item : orderItems) {
                UserBehaviorLog logEntity = new UserBehaviorLog();
                logEntity.setId(System.currentTimeMillis() + item.getProduct().getId()); // 确保ID唯一
                logEntity.setUserId(userId);
                logEntity.setSessionId(sessionId);
                logEntity.setEventType("purchase");
                logEntity.setProductId(item.getProduct().getId());
                logEntity.setCategory(item.getProduct().getCategory());
                logEntity.setPageUrl("/order/create");
                logEntity.setTimestamp(LocalDateTime.now());
                logEntity.setDate(LocalDateTime.now());
                
                userBehaviorRepository.saveUserBehaviorLog(logEntity);
            }
            log.info("Purchase behavior recorded: userId={}, items={}", userId, orderItems.size());
        } catch (Exception e) {
            log.error("Failed to record purchase behavior", e);
        }
    }

    /**
     * 批量记录用户行为
     */
    @Async
    public void batchRecordUserBehavior(List<UserBehaviorLog> logs) {
        try {
            userBehaviorRepository.batchSaveUserBehaviorLogs(logs);
            log.info("Batch user behavior recorded: {} logs", logs.size());
        } catch (Exception e) {
            log.error("Failed to batch record user behavior", e);
        }
    }

    /**
     * 获取用户行为统计
     */
    public Map<String, Object> getUserBehaviorStats(Long userId, LocalDateTime startDate, LocalDateTime endDate) {
        return userBehaviorRepository.getUserBehaviorStats(userId, startDate, endDate);
    }

    /**
     * 获取热门商品排行
     */
    public List<HotProduct> getHotProducts(int limit) {
        return userBehaviorRepository.getHotProducts(limit);
    }

    /**
     * 获取用户画像
     */
    public UserProfile getUserProfile(Long userId) {
        return userBehaviorRepository.getUserProfile(userId);
    }

    /**
     * 获取实时PV/UV统计
     */
    public Map<String, Object> getRealTimePvUv() {
        return userBehaviorRepository.getRealTimePvUv();
    }

    /**
     * 获取转化率统计
     */
    public Map<String, Object> getConversionRate(LocalDateTime startDate, LocalDateTime endDate) {
        return userBehaviorRepository.getConversionRate(startDate, endDate);
    }

    /**
     * 获取今日用户行为统计
     */
    public Map<String, Object> getTodayBehaviorStats() {
        LocalDateTime startOfDay = LocalDate.now().atStartOfDay();
        LocalDateTime endOfDay = LocalDate.now().atTime(23, 59, 59);
        
        Map<String, Object> pvUv = getRealTimePvUv();
        Map<String, Object> conversion = getConversionRate(startOfDay, endOfDay);
        
        // 合并统计数据
        pvUv.putAll(conversion);
        return pvUv;
    }

    /**
     * 获取用户最近行为统计
     */
    public Map<String, Object> getUserRecentBehaviorStats(Long userId, int days) {
        LocalDateTime endDate = LocalDateTime.now();
        LocalDateTime startDate = endDate.minusDays(days);
        return getUserBehaviorStats(userId, startDate, endDate);
    }

    /**
     * 获取客户端IP地址
     */
    private String getClientIpAddress(HttpServletRequest request) {
        String xForwardedFor = request.getHeader("X-Forwarded-For");
        if (xForwardedFor != null && !xForwardedFor.isEmpty() && !"unknown".equalsIgnoreCase(xForwardedFor)) {
            return xForwardedFor.split(",")[0].trim();
        }
        
        String xRealIp = request.getHeader("X-Real-IP");
        if (xRealIp != null && !xRealIp.isEmpty() && !"unknown".equalsIgnoreCase(xRealIp)) {
            return xRealIp;
        }
        
        return request.getRemoteAddr();
    }
}